<template>
  <el-checkbox-group v-model="viewModel" v-if="flag">
    <el-checkbox v-for="(item, index) in keyValues" :label="item.key" :key="index">{{item.value}}</el-checkbox>
  </el-checkbox-group>
</template>


<script>
  import api from '@/service/api'
  export default {
    model: {
      prop: 'dataModel',
      event: 'change'
    },
    props: {
      type: {},
      min: {
        default: 0
      },
      max: {
        default: 0
      },
      apiUrl: {}, // Api网址，优 先从Api中获取数据
      dataModel: {},
      watchValue: {} // 用于刷新数据
    },
    data () {
      return {
        keyValues: null,
        flag: false,
        viewModel: []
      }
    },
    mounted () {
      this.init()
    },
    methods: {
      async init () {
        this.flag = false
        this.keyValues = []
        if (!this.keyValues || this.keyValues.length === 0) {
          this.keyValues = await api.typeKeyValues(this.type, this.apiUrl)
          if (!this.keyValues) {
            this.keyValues = []
          }
        }
        if (this.dataModel) {
          if (typeof this.dataModel === 'string') {
            var data = this.dataModel.split(',')
            this.viewModel = data
          } else {
            this.viewModel = this.dataModel
          }
        }
        this.flag = true
      }
    },
    watch: {
      viewModel: {
        deep: true,
        handler (val) {
          this.$emit('change', this.viewModel)
        }
      },
      watchValue() {
        this.init()
      }
    }
  }
</script>

